import axios from 'axios';
import router from '@/router';

axios.defaults.timeout = 5000;
axios.defaults.baseURL ='http://192.168.1.13:8888'; //填写域名

//http request 拦截器
axios.interceptors.request.use(
    config => {
        config.data = JSON.stringify(config.data);
        config.headers = {
            'Content-Type':'application/json',
            'Authorization': 'Bearer '+localStorage.getItem('token')
        };
        return config;
    },
    error => {
        return Promise.reject(err);
    }
);

//响应拦截器即异常处理
axios.interceptors.response.use(response => {
    return response
}, err => {
    if (err && err.response) {
        switch (err.response.status) {
            case 400:
                console.log('错误请求')
                break;
            case 401:
                router.push({path:'/'})
                console.log('未授权，请重新登录')
                break;
            case 403:
                router.push({path:'/'})
                console.log('拒绝访问')
                break;
            case 404:
                console.log('请求错误,未找到该资源')
                break;
            case 405:
                console.log('请求方法未允许')
                break;
            case 408:
                console.log('请求超时')
                break;
            case 500:

                console.log('服务器端出错')
                break;
            case 501:
                console.log('网络未实现')
                break;
            case 502:
                console.log('网络错误')
                break;
            case 503:
                console.log('服务不可用')
                break;
            case 504:
                console.log('网络超时')
                break;
            case 505:
                console.log('http版本不支持该请求')
                break;
            default:
                console.log(`连接错误${err.response.status}`)
        }
    } else {
        console.log('连接到服务器失败')
    }
    return Promise.resolve(err.response)
})


/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function fetch(url,params={}){
    return new Promise((resolve,reject) => {
        axios.get(url,{
            params:params
        })
            .then(response => {
                resolve(response.data);
            })
            .catch(err => {
                reject(err)
            })
    })
}


/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url,data = {}){
    return new Promise((resolve,reject) => {
        axios.post(url,data)
            .then(response => {
                resolve(response.data);
            },err => {
                reject(err)
            })
    })
}

/**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function patch(url,data = {}){
    return new Promise((resolve,reject) => {
        axios.patch(url,data)
            .then(response => {
                resolve(response.data);
            },err => {
                reject(err)
            })
    })
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url,data = {}){
    return new Promise((resolve,reject) => {
        axios.put(url,data)
            .then(response => {
                resolve(response.data);
            },err => {
                reject(err)
            })
    })
}

/**
 * 下面是获取数据的接口
 */
/**
 * 测试接口
 * 名称：exam
 * 参数：paramObj/null
 * 方式：fetch/post/patch/put
 */

export const api = {

    //** 登录
    login: function(paramObj){
        return post('/api/v1/users/login',paramObj);
    },
    // 获取登录验证码
    getCodeImage: function() {
        return fetch('/api/v1/users/login/captcha');
    },
    //注销
    logout(){
      return fetch('/api/v1/users/logout/now')
    },
    //END 登录
    //**用户管理
    //用户管理的获取用户信息列表
    getUserInfoList:function(pageNum){
        return fetch('/api/v1/user/list/'+pageNum)
    },
    //搜索用户信息列表中的数据
    getUserInfoListSearch(pageNum, search) {
        return fetch('/api/v1/user/list/'+search+'/'+pageNum)
    },
    //查询子部门
    queryingSubsetDepartments(departmentId){
        return fetch('/api/v1/user/departments/subset?departmentId='+departmentId)
    },
    //查询个人信息
    getUserInfo(){
        return fetch('/api/v1/user/info')
    },
    //添加部门
    insterDepartments(data){
        return post('/api/v1/user/department/inster',data);
    },
    //查询当前部门下的部门
    selectDepartmentUser(departmentId,pageNum){
        return fetch('/api/v1/user/list/department/'+departmentId+'/'+pageNum)
    },
    //查询没有部门的人员
    notDepartment(pageNum){
        return fetch('/api/v1/user/list/not/deparement/'+pageNum)
    },
    /**
     * 向部门添加人员
     */
    departmentAddPeopleParam(data){
        return post('/api/v1/user/deparement/inster/user',data)
    },
    // 搜索下级用户
    selectSubsetDepartmentUser(select){
        return fetch('/api/v1/user/subset/deparement/user/search?select='+select)
    },
    //查询详细信息
    detailedInformation(id){
        return fetch('/api/v1/user/detailed/information?userId='+id);
    },
    //删除用户
    deleteUser(id){
        return fetch('/api/v1/user/delete?userId='+id);
    },
    //查询公寓下级部门
    queryingSubsetApartmentId(departmentId){
      return fetch('/api/v1/user/apartment/subset?departmentId='+departmentId)
    },
    //添加公寓部门
    insterApartment(data){
        return post('/api/v1/user/apartment/inster',data);
    },
    //查询权限信息
    getRoleInfo(userId){
        return fetch('/api/v1/user/get/one/user/role?userId='+userId)
    },
    //END用户管理
    //**餐别管理
    selectDepartmentSubsidy(departmentId){
      return fetch('/api/v1/subsidy/select/department?departmentId='+departmentId)
    },
    saveSubsidyDepartment(departmentId,data){
        return post('/api/v1/subsidy/save/department/'+departmentId,data)
    },
    selectTbDepartmentSubsidyUpdateTime(departmentId){
        return fetch('/api/v1/subsidy/select/department/time?departmentId='+departmentId)
    },
    saveTbDepartmentSubsidyUpdateTime(data){
        return post('/api/v1/subsidy/save/department/time',data)
    },
    //end餐别管理
    //**公寓科管理
    getQRCode(departmentId){
        return fetch('/api/v1/apartment/get/qrcode?department='+departmentId)
    },
    //end公寓科管理
    //**权限管理
    //保存权限
    savePermission(userId,data){
        return post('/api/v1/permission/update/one/user/'+userId,data)
    },
    //批量取消餐补权限
    cancelSubsidy(data){
        return post('/api/v1/permission/cancel/subsidy',data)
    },
    //end权限管理
    //**首页轮播图修改
    getAllHomeImage(){
        return fetch('/api/v1/phone/get/all/home/images')
    },
    updateHomeImages(imgdataOrId){
        return post('/api/v1/phone/update/images',imgdataOrId)
    },
    //end首页轮播图修改

    //**公告相关API
    //增加公告
    addInformation(data){
        return post('/api/v1/phone/add/information',data)
    },
    //查询公告
    selectInformations(pageNum){
        return fetch('/api/v1/phone/select/all/information/now?pagenum='+pageNum)
    },
    //更新公告
    updateInformations(data){
        return post('/api/v1/phone/update/information',data)
    },
    //删除公告
    deleteInformations(id){
        return fetch('/api/v1/phone/delete/information?informationid='+id)
    },
    //置顶公告
    topInformations(id){
        return fetch('/api/v1/phone/top/information?informationid='+id)
    },
    //END公告
    //**增加评论
    // 查询公告
    selectDiscuss(pageNum){
        return fetch('/api/v1/phone/select/all/discuss/now?pageNum='+pageNum)
    },
    //删除评论
    deleteDiscuss(discussid){
        return fetch('/api/v1/phone/admin/delete/discuss?discussid='+discussid)
    },
    getStatements(pageNum){
        return fetch('/api/v1/statements/apartment/list/allorder/'+pageNum+'?orderStatus=3')
    }


};
